package com.qding.park.manager.web.controller;

import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.qding.park.common.core.annotation.log.OperationLogType;
import com.qding.park.common.core.annotation.log.SystemControllerLog;
import com.qding.park.common.core.exceptions.ExceptionMessage;
import com.qding.park.common.core.exceptions.business.validator.RchlValidatorException;
import com.qding.park.common.core.exceptions.system.SystemUnKnown;
import com.qding.park.common.core.validate.RchlValidateBean;
import com.qding.park.common.core.validate.RchlValidateTools;
import com.qding.park.common.utils.DateUtils;
import com.qding.park.common.utils.export.DataField;
import com.qding.park.common.utils.export.ExportDataSource;
import com.qding.park.common.utils.export.excel.ExcelDataExportor;
import com.qding.park.common.utils.export.excel.MODE;
import com.qding.park.common.web.controller.BaseController;
import com.qding.park.manager.common.pojo.ParkDataResult;
import com.qding.park.manager.common.rest.domain.AnswerMsg;
import com.qding.park.manager.common.rest.domain.AnswerMsgFactoryImpl;
import com.qding.park.manager.common.rest.enums.ResponseCodeEnum;
import com.qding.park.manager.facade.statis.service.InviteStatisFacade;
import com.qding.park.manager.pojo.PowerInfo;
import com.qding.park.manager.pojo.TbInvitecard;
import com.qding.park.manager.pojo.enums.VisitPurposeEnum;
import com.qding.park.manager.pojo.example.TbInviteExample;
import com.qding.park.manager.pojo.example.TbInviteExample.Criteria;
import com.qding.park.manager.service.statis.biz.InviteStatisBiz;
import com.qding.park.manager.service.statis.mapper.TbInvitecardStatisMapper;
import com.qding.park.manager.web.form.InviteListForm;
import com.qding.park.manager.web.power.Power;

/**
 * @ClassName: Web_InviteController
 * @Description: 预定
 * @author Comsys-Administrator
 * @date 2016年10月12日 下午3:48:49
 */
@RestController
@RequestMapping("/invite")
public class Web_InviteController extends BaseController {

    private static final Logger _log = LoggerFactory.getLogger(Web_InviteController.class);

    /**
     * @Fields inviteFacade : TODO（邀请业务）
     */
    @Autowired
    private InviteStatisFacade inviteFacade;

    @Autowired
    private TbInvitecardStatisMapper tbInvitecardMapper;

    @Autowired
    private InviteStatisFacade inviteStatisFacade;

    @Autowired
    private InviteStatisBiz inviteStatisBiz;

    @Power(visitPark = "#parkId")
    @SystemControllerLog(description = "邀请参数查询", operation = OperationLogType.invite_params)
    @RequestMapping("/params")
    public AnswerMsg params(String parkId) {

        /****** 验证字段 ********/
        RchlValidateBean vb = new RchlValidateBean();
        vb.getRequiredValidate().put("parkId", parkId);

        vb.getIntValidate().put("parkId", parkId);
        RchlValidateTools.validate(vb);
        /**************/
        ParkDataResult dataResult = inviteFacade.inviteParams(Integer.valueOf(parkId));
        AnswerMsg answerMsg = AnswerMsgFactoryImpl.createAnswerMsg(dataResult.getData());
        return answerMsg;
    }

    @Power(visitPark = "#parkId")
    @SystemControllerLog(description = "邀请参数设置", operation = OperationLogType.invite_params_set)
    @RequestMapping("/params/set")
    public AnswerMsg params_set(String parkId, String visitorCheck) {

        /****** 验证字段 ********/
        RchlValidateBean vb = new RchlValidateBean();
        vb.getRequiredValidate().put("parkId", parkId);
        vb.getRequiredValidate().put("visitorCheck", visitorCheck);

        vb.getIntValidate().put("parkId", parkId);
        vb.getIntValidate().put("visitorCheck", visitorCheck);
        RchlValidateTools.validate(vb);

        if (Integer.valueOf(visitorCheck) != 0 && Integer.valueOf(visitorCheck) != 1) {
            throw new RchlValidatorException(RchlValidatorException.TypeEnum.EXCEPTION_VALIDATOR.getId(), null,
                    new ExceptionMessage(RchlValidatorException.TypeEnum.EXCEPTION_VALIDATOR.getDesc(),
                            "visitorCheck 值不合法", "parkId=" + parkId + ",visitorCheck=" + visitorCheck));
        }
        /**************/
        ParkDataResult dataResult = inviteFacade.setInviteParams(Integer.valueOf(parkId),
                Integer.valueOf(visitorCheck));
        AnswerMsg answerMsg = AnswerMsgFactoryImpl.createAnswerMsg(dataResult.getData());
        return answerMsg;
    }

    /**
     * @param parkId
     *            车场编号
     * @param carNum
     *            车牌号
     * @param jumpPage
     *            当前页码
     * @param pageLength
     *            当前页长度
     * @return
     */
    @Power(visitPark = "#form.getParkId()")
    @SystemControllerLog(description = "邀请单查询", operation = OperationLogType.invite_list)
    @RequestMapping("/list")
    public AnswerMsg list(@Valid InviteListForm form, BindingResult result) {

        /* 解析验证结果 */
        super.analysisValid(result);
        /* 解析验证结果 */

        PowerInfo power = this.getPowerInfo();

        int jumpPageInt = Integer.valueOf(form.getJumpPage());
        int pageLengthInt = Integer.valueOf(form.getPageLength());

        // 初始化统计条件
        TbInviteExample example = new TbInviteExample();
        Criteria criteria = example.createCriteria();

        if (!StringUtils.isBlank(form.getParkId())) {
            // 车场号
            criteria.andParkIdEqualTo(form.getParkId());
        }
        if (!StringUtils.isBlank(form.getCarNum())) {
            // 车牌号
            criteria.andCarnumLike(form.getCarNum());
        }

        if (!power.isAdminIs()) {
            criteria.andParkIdIn(power.getParkList());
        }

        ParkDataResult dataResult = inviteStatisFacade.invitelist(example, jumpPageInt, pageLengthInt);
        AnswerMsg answerMsg = AnswerMsgFactoryImpl.createAnswerMsg(dataResult.getData());
        return answerMsg;
    }

    /**
     * @param startTime
     *            开始时间
     * @param endTime
     *            结束时间
     * @return
     */
    @Power(visitPark = "#parkId")
    @SystemControllerLog(description = "邀请单导出", operation = OperationLogType.invite_exportExcel)
    @RequestMapping("/exportExcel")
    @ResponseBody
    public AnswerMsg exportExcel(String startTime, String endTime, String parkId) {

        try {
            /****** 验证字段 ********/
            /**************/
            PowerInfo power = this.getPowerInfo();
            // 初始化统计条件
            final TbInviteExample example = new TbInviteExample();
            Criteria criteria = example.createCriteria();

            if (!power.isAdminIs()) {
                criteria.andParkIdIn(power.getParkList());
            }
            if (!StringUtils.isBlank(startTime)) {
                // 缴费开始时间
                criteria.andCreateTimeGreaterThanOrEqualTo(
                        DateUtils.parseDate(startTime, DateUtils.DATE_FORMAT_DATETIME));
            }
            if (!StringUtils.isBlank(endTime)) {
                // 缴费开始时间
                criteria.andCreateTimeLessThanOrEqualTo(DateUtils.parseDate(endTime, DateUtils.DATE_FORMAT_DATETIME));
            }

            if (!StringUtils.isBlank(parkId)) {
                criteria.andParkIdEqualTo(parkId);
            }
            // 排序
            example.orderByCreateTimeDesc();

            final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            final SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            final SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss");
            String filename = "邀请单报表_" + sdf2.format(new Date());
            response.setHeader("Content-disposition",
                    "attachment; filename=" + URLEncoder.encode(filename + ".xls", "utf-8"));
            OutputStream os = response.getOutputStream();
            DataField[] dataFields = new DataField[7];
            dataFields[0] = new DataField("订单号", "orderNum", 20);
            dataFields[1] = new DataField("订单状态", "orderStatus", 25);
            dataFields[2] = new DataField("用户账号", "tel", 20);
            dataFields[3] = new DataField("邀请车牌", "carNum", 20);
            dataFields[4] = new DataField("来访日期", "inviteTime", 30);
            dataFields[5] = new DataField("来访目的", "visitPurpose", 20);
            dataFields[6] = new DataField("当前状态", "currentStatus", 40);

            new ExcelDataExportor<Object>(dataFields, new ExportDataSource<Object>() {

                @Override
                public List getData() {
                    // 查询统计条件
                    List<TbInvitecard> invitecardList = tbInvitecardMapper.listByExample(example);
                    List<Map<String, Object>> lists = new ArrayList<Map<String, Object>>();
                    int temp = 0;
                    for (int i = 0; i < invitecardList.size(); i++) {
                        Map<String, Object> mapParam = new HashMap<String, Object>();
                        TbInvitecard tbInvitecard = invitecardList.get(i);
                        temp = i;
                        mapParam.put("orderNum", tbInvitecard.getId());
                        mapParam.put("orderStatus", inviteStatisBiz.getOrderStatusStr(tbInvitecard));
                        mapParam.put("tel", tbInvitecard.getTel());
                        mapParam.put("carNum", tbInvitecard.getCarNum());
                        mapParam.put("inviteTime", tbInvitecard.getStartTime() == null ? ""
                                : DateUtils.formatDate(tbInvitecard.getStartTime(), DateUtils.DATE_FORMAT_DATEONLY));
                        // 预定结束时间
                        mapParam.put("visitPurpose", VisitPurposeEnum.tranDesc(tbInvitecard.getVisitPurpose()));
                        mapParam.put("currentStatus", inviteStatisBiz.getCurrentStatus(tbInvitecard));
                        lists.add(mapParam);
                    }
                    return lists;
                }
            }, os, MODE.EXCEL).export();

            AnswerMsg answerMsg = AnswerMsgFactoryImpl.createAnswerMsg(null);
            return answerMsg;
        } catch (Exception e) {
            SystemUnKnown ex = new SystemUnKnown(e, ExceptionMessage.createExceptionMessage(SystemUnKnown.default_Name,
                    "未知Exception", "payStartTime=" + startTime + ",payEndTime=" + endTime));
            exceptionHandle.handle(ex);
            AnswerMsg answerMsg = AnswerMsgFactoryImpl.createErrorAnserMsg(ResponseCodeEnum.SYSTEM_ERROR);
            return answerMsg;
        }
    }
}
